package com.ccp.dev.system.configuration;

import org.apache.commons.codec.binary.Base64;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;

/**
 *自定义security密码加密
 * @author y
 */
public class CustomPwdEncoder implements PasswordEncoder {
	/**
	 * 设置是否忽略密码 TODO 这个 ThreadLocal之后需要修改
	 */
	private static ThreadLocal<Boolean> ingorePwd=new ThreadLocal<>();

	public static void setIngore(boolean ingore){
		ingorePwd.set(ingore);
	}

	/**
	 * 对明文密码进行加密
	 * @param rawPassword  明文密码
	 * @return 加密后的密码
	 */
	@Override
    public String encode(CharSequence rawPassword){
    	String pwd=rawPassword.toString();
    	try {
    		MessageDigest md = MessageDigest.getInstance("SHA-256");
    		byte[] digest= md.digest(pwd .getBytes("UTF-8"));
    		return new String(Base64.encodeBase64(digest));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 设置是否忽略密码
	 * @param rawPassword     明文密码
	 * @param encodedPassword 数据库中用户加密后的密码
	 * @return <code>true</code>匹配成功 <code>false</code>匹配失败
	 */
	@Override
    public  boolean matches(CharSequence rawPassword, String encodedPassword){
		if(ingorePwd.get()==null || ingorePwd.get()==false){
			String enc=this.encode(rawPassword);
			return enc.equals(encodedPassword);
		}
		return true;
    }
}
